using UnityEngine;
using UnityEngine.EventSystems;

namespace Gj
{
    public class ScreenRockerInputHelper : NodeHelper, IPointerDownHandler, IPointerUpHandler, IDragHandler
    {
        public float size;
        public bool invert;
        public KeyCode keyCode = KeyCode.None;
        private bool allow;
        private float radius;
        private Vector2 startPosition;

        protected override BindDataType bindDataType => BindDataType.Bool;

        protected override void Start()
        {
            radius = size / 2;
            base.Start();
        }

        private void Update()
        {
            if (keyCode == KeyCode.None) return;
            if (!allow) return;

#if UNITY_IPHONE || UNITY_ANDROID
#elif UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX
            if (Input.GetKeyDown(keyCode)) Emit(UIEvent.Enter);
            if (Input.GetKeyUp(keyCode)) Emit(UIEvent.Leave);
#endif
        }

        public void OnDrag(PointerEventData eventData)
        {
            if (!allow) return;
            Emit(UIEvent.Move);
            var position = GetPosition(eventData.position.x, eventData.position.y);
            ChangeValue(position.x / radius, position.y / radius);
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            if (!allow) return;
            Emit(UIEvent.Enter);
            startPosition = eventData.position;
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            if (!allow) return;
            startPosition = Vector2.zero;
            ChangeValue(0, 0);
            Emit(UIEvent.Leave);
        }

        protected override void BindData(bool b)
        {
            allow = invert ? !b : b;
        }

        private void ChangeValue(float x, float y)
        {
            SystemInput.sh = x;
            SystemInput.sv = y;
        }

        private bool IsOut(float x, float y)
        {
            //计算两坐标点之间的距离
            return Vector2.Distance(new Vector2(x, y), new Vector2(0, 0)) > radius;
        }

        private Vector2 GetPosition(float x, float y)
        {
            var targetX = x - startPosition.x;
            var targetY = y - startPosition.y;
            if (IsOut(targetX, targetY))
            {
                //获取x，y坐标点弧度
                var radians = Mathf.Atan2(targetX, targetY);
                //sin和cos对应的是弧度不是角度
                return new Vector2(Mathf.Sin(radians) * radius, Mathf.Cos(radians) * radius);
            }

            return new Vector2(targetX, targetY);
        }
    }
}